package com.chengxiaoxiao.utils;

import com.chengxiaoxiao.domain.Books;
import com.chengxiaoxiao.domain.Borrow;
import com.chengxiaoxiao.domain.Order;
import com.chengxiaoxiao.service.BookService;
import com.chengxiaoxiao.service.BorrowService;
import com.chengxiaoxiao.service.OrderService;
import com.chengxiaoxiao.service.impl.BookServiceImpl;
import com.chengxiaoxiao.service.impl.BorrowServiceImpl;
import com.chengxiaoxiao.service.impl.OrderServiceImpl;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 定时任务管理类
 */
public class MyJob implements Job {

    BookService bookService = new BookServiceImpl();
    BorrowService borrowService = new BorrowServiceImpl();
    OrderService orderService = new OrderServiceImpl();

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //TODO:

        //查询已经过期的书籍
        loadPushExpireTime();


        //查询预定书籍情况
        List<Order> list = orderService.get();
        for(int i=0;i<list.size();i++){
            Order o = list.get(i);
            Books b =bookService.getbyId(o.getBookId());

            if(b.getNumber()>0)
            {
                JPushUtils.push("尊敬的用户您好，您预定的书籍：" + b.getBookName()+ ",已有人归还，请尽快到校图书馆进行借阅");
            }
        }

    }

    /**
     * 加载过期的书籍，并发送通知
     */
    private void loadPushExpireTime() {

        List<Borrow> list = borrowService.getExpire();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            Borrow b = list.get(i);

            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
            String expire = f.format(b.getExpireTime());

            sb.append(b.getBook().getBookName() + "将于：" + expire + "过期。");
        }
        JPushUtils.push("尊敬的用户您好，您节约的书籍：" + sb.toString() + "请尽快到校图书馆进行归还");


    }


}
